package Practice;

import java.util.*;

public class BinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        public TreeNode(char val) {
            this.val = val;
        }
    }


    /**
     * 创建一棵二叉树 返回这棵树的根节点
     *
     * @return
     */
    public static int i=0;
    public TreeNode createTree(String str) {
        char ch = str.charAt(i);
        TreeNode root = null;
        if(ch!='#'){
            root=new TreeNode(ch);
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else{
            i++;
        }
        return root;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root ==null){
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    void inOrder(TreeNode root) {
        if(root==null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root) {
        if(root==null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    public static int nodeSize;

    /**
     * 获取树中节点的个数：遍历思路
     */
    void size(TreeNode root) {
        if(root==null){
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    /**
     * 获取节点的个数：子问题的思路
     *
     * @param root
     * @return
     */
    int size2(TreeNode root) {
        if(root==null){
            return 0;
        }
        return size2(root.left)+size2(root.right)+1;
    }


    /*
     获取叶子节点的个数：遍历思路
     */
    public static int leafSize = 0;

    void getLeafNodeCount1(TreeNode root) {
        if(root==null){
            return;
        }
        if(root.left==null&&root.right==null){
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    /*
     获取叶子节点的个数：子问题
     */
    int getLeafNodeCount2(TreeNode root) {
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        return getLeafNodeCount2(root.left)+getLeafNodeCount2(root.right);
    }

    /*
    获取第K层节点的个数
     */
    int getKLevelNodeCount(TreeNode root, int k) {
        if(root == null){
            return 0;
        }
        if(k==1){
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
    }

    /*
     获取二叉树的高度
     时间复杂度：O(N)
     */
    int getHeight(TreeNode root) {
        if(root==null){
            return 0;
        }
        int count1 = getHeight(root.left);
        int count2 = getHeight(root.right);
        int tmp = count1>count2?count1:count2;

        return tmp+1;
    }


    public boolean isBalanced(TreeNode root){
        if(root==null){
            return true;
        }
        int lf = getHeight(root.left);
        int rg = getHeight(root.right);
        if(Math.abs(lf-rg)<2&&isBalanced(root.left)&&isBalanced(root.right)){
            return true;
        }
        return false;
    }


    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if(root==null){
            return null;
        }
        TreeNode lef = find(root.left,val);
        if(lef!=null){
            return lef;
        }
        TreeNode rig = find(root.right,val);
        if(rig!=null){
            return rig;
        }
        return null;
    }

    //层序遍历
    void levelOrder(TreeNode root) {
        if(root==null){
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur= queue.poll();
            System.out.println(cur.val+" ");
            if(cur.left!=null){
                queue.offer(cur.left);
            }
            if(cur.right!=null){
                queue.offer(cur.right);
            }
        }
    }


    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if(root==null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while (!queue.isEmpty()){
            if(queue.poll()!=null){
                return false;
            }
        }
        return true;
    }

    //判断root是否对称
    public boolean isSymmetriChild(TreeNode root){
        if(root==null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode lt,TreeNode rt){
        //1.为空
        if(lt==null&&rt!=null||lt!=null&&rt==null){
            return false;
        }
        if(lt==null&&rt==null){
            return true;
        }
        //2.不为空
        if(lt.val!= rt.val){
            return false;
        }
        //同时满足
        return isSymmetricChild(lt.left,rt.right)&&isSymmetricChild(lt.right,rt.left);

    }


    //反转二叉树
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        if(root.left==null&&root.right==null){
            return root;
        }
        TreeNode tmp = root.left;
        root.left =root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

//判断两树是否相同
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null&&q!=null||p!=null&&q==null){
            return false;
        }
        if(p==null&&q==null) {
            return true;
        }
        if(p.val!= q.val){
            return false;
        }

        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
    }



//另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root ==null){
            return false;
        }
        if(isSameTree(root,subRoot)){
            return true;
        }
        if(isSubtree(root.left,subRoot)){
            return true;
        }
        if(isSubtree(root.right,subRoot)){
            return true;
        }
        return false;
    }

    public List<List<Character>> levelOrder1(TreeNode root) {
        List<List<Character>> reList = new ArrayList<>();
        if(root==null){
            return reList;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Character> list = new ArrayList<>();
            while(size!=0){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                size--;
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            reList.add(list);
        }
        return reList;
    }


    //自下而上的层序遍历

    public List<List<Character>> reList = new ArrayList<>();

    public List<List<Character>> getReList1(TreeNode root){
        List<List<Character>> relist2 = new ArrayList<>();
        levelOrderBottom(root);
        for(int i = reList.size()-1;i>0;i--){
            relist2.add(reList.get(i));
        }
        return relist2;
    }
    public List<List<Character>> levelOrderBottom(TreeNode root) {
        if(root==null){
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Character> List1 = new ArrayList<>();
            int size = queue.size();
            while(size>0){
                TreeNode cur = queue.poll();
                List1.add(cur.val);
                size--;
                if(cur.left!=null){
                    queue.offer(cur.left);
                }
                if(cur.right!=null){
                    queue.offer(cur.right);
                }
            }
            reList.add(List1);
        }
        return  reList;
    }

    //根据二叉树创建字符串
    public String treeStr(TreeNode root){
        StringBuilder sbu = new StringBuilder();
        treeStrChlid(root,sbu);
        return sbu.toString();
    }

    public void treeStrChlid(TreeNode root,StringBuilder sbu){
        if(root==null){
            return;
        }
        sbu.append(root.val);

        //1.先递归左数
        if(root.left!=null){
            sbu.append('(');
            treeStrChlid(root.left,sbu);
            sbu.append(')');//一棵树走完了
        }else{
            if(root.right==null){
                return;
            }else{
                sbu.append("()");
            }
        }

        //2.递归右数
        if(root.right!=null){
            sbu.append('(');
            treeStrChlid(root.right,sbu);
            sbu.append(')');
        }
        else{
            return;
        }
    }

    //非递归前序遍历(根左右)
    /*
    利用栈后进先出的特点,不满足条件的就按照顺序入栈,一旦满足条件就直接出栈
     */
    public List<Character> preorderTraversal(TreeNode root){
        List<Character> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null||!stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return list;
    }


    //非递归中序遍历(左根右)
    public List<Character> inorderTraversal(TreeNode root){
        List<Character> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur!=null||!stack.isEmpty()){
            while(cur.left!=null){
                stack.push(cur);
                cur=cur.left;
            }
            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }


    //非递归后序遍历(左右根)

    public List<Character> postorderTraversal(TreeNode root){
        List<Character> list = new ArrayList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur!=null||!stack.isEmpty()){
            while(cur.left!=null){
                stack.push(cur);
                cur=cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right==null||top.right==prev){
                stack.pop();
                list.add(top.val);
                prev = top;
            }else{
                cur = cur.right;
            }
        }
        return list;
    }


    //判断两个节点的公共祖先
    /*
    1.先判断q或者p是不是root的其中一个
    2.左子树中查找q/p
    3.右子树
    root的两侧为空不为空--》右侧找到的就是公共祖先
    root的左侧为空 右侧不为空--》右侧找到的就是公共祖先
     */
    public TreeNode lowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
        if(root==null){
            return null;
        }
        if(root==p||root==q){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
            return root;
        }else if(left!=null){
            return left;
        }else{
            return right;
        }
    }

    //寻找公共祖先方法2
    /*
    1.只要root不为null 就放在栈中
    2.再判断当前节点 左子树 右子树 是不是有要找的节点 如果没有就出栈
    3.root==node 找到了指定节点
    4.栈里面存储的是找到指定节点的路径
     */

    public boolean getWay(TreeNode root,TreeNode node, Stack<TreeNode> stack){
        if(root==null){
            return false;
        }
        stack.push(root);
        if(root==node){
            return true;
        }

        boolean lf = getWay(root.left,node,stack);
        if(lf){
            return true;
        }

        boolean rg = getWay(root.right,node,stack);
        if(rg){
            return true;
        }

        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor1(TreeNode root,TreeNode p,TreeNode q){
        if(root==null){
            return null;
        }

        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();

        getWay(root,p,stack1);
        getWay(root,q,stack2);

        int size1 = stack1.size();
        int size2 = stack2.size();
        if(size1>size2) {
            int i = size1 - size2;
            while (i != 0) {
                stack1.pop();
                i--;
            }
        }else{
            int i = size2-size1;
            while (i!=0){
                stack2.pop();
                i--;
            }
        }
       while(!stack1.isEmpty()&&!stack2.isEmpty()){
           if(stack1.peek().equals(stack2.peek())){
               return stack1.pop();
           }else{
               stack1.pop();
               stack2.pop();
           }
       }
        return null;
    }



    //从前序与中序遍历序列构造二叉树
    /*public  int preIndex ;
    public TreeNode buildTree(char[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    private TreeNode buildTreeChild(char[] preorder, int[] inorder,int inBegin,int inEnd) {
        if(inBegin > inEnd) {
            return null;
        }
        //1、创建根节点
        TreeNode root =  new TreeNode(preorder[preIndex]);
        //2. 在中序遍历的字符串当中 找到当前根节点的下标
        int rootIndex = findRootIndex(inorder,inBegin,inEnd,preorder[preIndex]);
        preIndex++;
        //3. 分别创建左子树和右子树
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inEnd);
        return root;
    }

    private int findRootIndex(int[] inorder,int inBegin,int inEnd,int key) {
        for(int i = inBegin; i <= inEnd;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }*/


    //从中序与后序遍历序列构造二叉树

}
